<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Http\Models\User;
use App\Http\Models\Smscode;
use Carbon\Carbon;
use Auth;
use DB;
use Validator;
use App\Http\Models\UserNameLog;
use App\Http\Models\Region;
use App\Http\Models\UserCapital;
use App\Http\Models\StatisticsUser;

class UserController extends Controller
{
    public function login()
    {
        return view('auth/login');
    }

    public function userInfo()
    {
        if (Auth::check()) {
            return response()->json(['code' => 0, 'msg' => 'ok', 'data' => Auth::user()]);
        }
        return response()->json(['code' => 1, 'msg' => '用户名未登陆']);
    }


    public function doLogin(Request $request)
    {
        $phone = $this->request->phone;
        $password = $this->getPassword($this->request->password);
        $data = $request->only(['phone', 'password']);
        $validator = Validator::make($data, [
            'phone' => 'required|max:11',
            'password' => 'required|max:40',
        ]);
        $error = $this->ErrorInfo($validator);
        if (count($error) > 0) {
            return response()->json(['code' => 1, 'msg' => '参数错误', 'data' => $error]);
        }
        if (!preg_match("/^1\d{10}$/", $phone)) {
            return response()->json(['code' => 1, 'msg' => '手机号不正确']);
        }
        if (Auth::attempt(['phone' => $phone, 'password' => $password])) {
            $user = $request->user();
            $tokenResult = $user->createToken('Personal Access Token');
            $token = $tokenResult->token;
            $token->expires_at = Carbon::now()->addHours(4);
            if ($request->remember_me)
                $token->expires_at = Carbon::now()->addDays(7);
            $token->save();
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => [
                    'access_token' => $tokenResult->accessToken,
                    'token_type' => 'Bearer',
                    'expires_at' => Carbon::parse($token->expires_at)->toDateTimeString()
                ]
            ]);
        } else {
            return response()->json(['code' => 1, 'msg' => '用户名或密码错误']);
        }
        die();
    }

    public function doLoginCode(Request $request)
    {
        $phone = $this->request->phone;
        $code = $this->request->code;

        $data = $request->only(['phone', 'code']);
        $validator = Validator::make($data, [
            'phone' => 'required|max:11',
            'code' => 'required|max:4',
        ]);
        $error = $this->ErrorInfo($validator);
        if (count($error) > 0) {
            return response()->json(['code' => 1, 'msg' => '参数错误', 'data' => $error]);
        }
        if (!preg_match("/^1\d{10}$/", $phone)) {
            return response()->json(['code' => 1, 'msg' => '手机号不正确']);
        }

        if (!Smscode::verify($phone, $code, 'login')) {
            return response()->json(['code' => 1, 'msg' => '验证码不正确']);
        }
        $user = User::where('phone', $phone)->first();
        if (empty($user)) {
            return response()->json(['code' => 1, 'msg' => '用户不存在']);
        }

        if (Auth::loginUsingId($user->id)) {
            $user = Auth::user();
            $tokenResult = $user->createToken('Personal Access Token');
            $token = $tokenResult->token;
            $token->expires_at = Carbon::now()->addHours(4);
            if ($request->remember_me)
                $token->expires_at = Carbon::now()->addDays(7);
            $token->save();
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => [
                    'access_token' => $tokenResult->accessToken,
                    'token_type' => 'Bearer',
                    'expires_at' => Carbon::parse($token->expires_at)->toDateTimeString()
                ]
            ]);
        }
        return response()->json(['code' => 1, 'msg' => '登陆失败']);
    }

    public function register()
    {
        return view('auth/register');
    }

    public function getSmscode()
    {
        $phone = $this->request->phone;
        $type = $this->request->type;
        $msg = '';

        if (!preg_match("/^1\d{10}$/", $phone)) {
            $msg = '手机号不正确';
        }

        if (!in_array($type, array('register', 'forgot', 'login'))) {
            $msg = '类型不正确';
        }

        $user = User::where('phone', $phone)->first();
        if ($type == 'register' && $user) {
            $msg = '用户已存在';
        } elseif ($type != 'register' && empty($user)) {
            $msg = '用户不存在';
        }
        if ($msg) {
            return response()->json(['code' => 1, 'msg' => $msg]);
        }

        if (!Smscode::send($phone, $type)) {
            return response()->json(['code' => 1, 'msg' => '发送验证码失败']);
        }
        return response()->json(['code' => 0, 'msg' => 'ok']);
    }

    public function doRegister()
    {
        $phone = $this->request->phone;
        $password = $this->request->password;
        $code = $this->request->code;

        if (!Smscode::verify($phone, $code, 'register')) {
            return json_encode(['code' => 1, 'msg' => '验证码不正确']);
        }
        $user = new User;
        $user->phone = $phone;
        $user->password = Hash::make($this->getPassword($password));
        $user->save();
        StatisticsUser::addRegisterUser();
        return response()->json(['code' => 0, 'msg' => '注册成功', 'data' => Auth::user()]);
    }

    public function logout()
    {
        $this->request->user()->token()->revoke();
        return response()->json(['code' => 0, 'msg' => 'ok']);
    }

    public function doResetPassword()
    {
        $old_password = $this->request->old_password;
        $new_password = $this->request->new_password;
        if (strlen($new_password) < 6) {
            return response()->json(['code' => 1, 'msg' => '密码至少6位数字和字母']);
        }
        $user = Auth::user();
        if (!Hash::check($this->getPassword($old_password), $user->password)) {
            return json_encode(['code' => 1, 'msg' => '旧密码不正确']);
        }
        $user->password = Hash::make($this->getPassword($new_password));
        $user->save();
        return response()->json(['code' => 0, 'msg' => 'ok']);
    }

    public function setting()
    {
        return view('auth/setting');
    }

    public function forgot()
    {
        return view('auth/forgot');
    }

    public function reseting()
    {
        return view('auth/reseting');
    }

    public function forgotReset()
    {
        $phone = $this->request->phone;
        $password = $this->request->password;
        $code = $this->request->code;
        if (strlen($password) < 6) {
            return response()->json(['code' => 1, 'msg' => '密码至少6位数字和字母']);
        }
        $user = User::where('phone', $phone)->first();
        if (empty($user)) {
            return response()->json(['code' => 1, 'msg' => '用户不存在']);
        }
        if (!Smscode::verify($phone, $code, 'forgot')) {
            return response()->json(['code' => 1, 'msg' => '验证码不正确']);
        }
        $user->password = Hash::make($this->getPassword($password));
        $user->save();
        // Auth::login($user, true);
        return response()->json(['code' => 0, 'msg' => 'ok']);
    }

    public function checkForgetcode(){
        $phone = $this->request->phone;
        $code = $this->request->code;
        $user = User::where('phone', $phone)->first();
        if (empty($user)) {
            return response()->json(['code' => 1, 'msg' => '用户不存在']);
        }
        if (!Smscode::verify($phone, $code, 'forgot')) {
            return response()->json(['code' => 1, 'msg' => '验证码不正确']);
        }
        return response()->json(['code' => 0, 'msg' => 'ok']);
    }

    private function getPassword($password)
    {
        return md5(md5("q05RbDInqSNNhMWuLE" . $password));
    }

    public function user(Request $request)
    {
        return response()->json($request->user());
    }


    /**
     * 个人信息修改
     */
    public function userEditInfo(Request $request)
    {
        $data = $request->only(['avatar', 'name', 'signature', 'city_id', 'province_id', 'qq']);
        $validator = Validator::make($data, [
            'name' => 'required|max:20|min:2',
            'signature' => 'required|max:200',
            'city_id' => 'required|numeric',
            'province_id' => 'required|numeric',
            //'area_id' => 'required|numeric',
            'qq' => 'required|numeric',
            //'avatar' => 'required|url',
        ]);
        $error = $this->ErrorInfo($validator);
        if (count($error) > 0) {
            return json_encode(['code' => 1, 'msg' => 'ng', 'data' => $error]);
        }
        $user = User::where('id', Auth::id())->first();
        $user->name = $data['name'];
        $user->signature = $data['signature'];
        $user->city_id = $data['city_id'];
        $user->province_id = $data['province_id'];
        // $user->area_id=$data['area_id'];
        if (isset($data['avatar']) && $data['avatar']) {
            $user->avatar = $data['avatar'];
        }
        if ($data['qq']) {
            $user->qq = $data['qq'];
        }
        $user->deleted_at = null;
        $bool = $user->save();
        if ($bool) {
            return json_encode(['code' => 0, 'msg' => '资料修改成功!', 'data' => '']);
        } else {
            return json_encode(['code' => 1, 'msg' => '资料修改失败!', 'data' => '']);
        }
    }

    public function getUserInfo()
    {
        $userInfo = User::select('avatar', 'name', 'signature', 'city_id', 'province_id', 'area_id', 'qq')
            ->where('id', Auth::id())
            ->first();
        if ($userInfo) {
            $userInfo = $userInfo->toArray();
            if ($userInfo['province_id']) {
                $userInfo['province'] = Region::select('name', 'id')->where('id', $userInfo['province_id'])->first();
            } else {
                $userInfo['province'] = [];
            }
            if ($userInfo['city_id']) {
                $userInfo['city'] = Region::select('name', 'id')->where('id', $userInfo['city_id'])->first();
            } else {
                $userInfo['city'] = [];
            }
            $data = UserCapital::select('voucher_number', 'integral')->where(['user_id' => Auth::id()])->first();
            if ($data) {
                $data = $data->toArray();
            } else {
                $data = ['voucher_number' => 0, 'integral' => 0];
            }
            return json_encode(['code' => 0, 'msg' => '获取数据成功!', 'data' => array_merge($userInfo, $data)]);
        } else {
            return json_encode(['code' => 1, 'msg' => '获取数据失败!',]);
        }
    }

    /**
     * 进行编辑用户的头像信息,并保存
     * @param Request $request
     * @return string
     */
    public function userEditAvatar(Request $request)
    {
        $data = $request->only(['avatar']);
        $validator = Validator::make($data, [
            'avatar' => 'required|url',
        ]);
        $error = $this->ErrorInfo($validator);
        if (count($error) > 0) {
            return json_encode(['code' => 1, 'msg' => $error[0], 'data' => $error]);
        }
        $img_error = ImageUrlValidate(['avatar' => $data['avatar']]);
        if ($img_error) {
            return json_encode(['code' => 1, 'msg' => $img_error[0], 'data' => '']);
        }
        $user = User::where('id', Auth::id())->first();
        $user->avatar = $data['avatar'];
        $user->deleted_at = null;
        $bool = $user->save();
        if ($bool) {
            return json_encode(['code' => 0, 'msg' => 'ok', 'data' => '']);
        } else {
            return json_encode(['code' => 1, 'msg' => 'ng', 'data' => '']);

        }
    }

    /**
     * 捕获validate的erroer数据
     * @param $validator
     * @return string
     */
    protected function ErrorInfo($validator)
    {
        $error = [];
        if ($validator->fails()) {
            $error_info = json_decode(json_encode($validator->errors(), true));
            foreach ($error_info as $key => $value) {
                $error[] = $value[0];
            }

        }
        return $error;
    }

}
